package com.zzw.springboot.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户行为分析工具类
 */
@Component
public class UserBehaviorAnalysisUtil {

    @Autowired
    private RedisUtil redisUtil;
    
    @Autowired
    private RedisRankingUtil rankingUtil;

    private static final String USER_DAILY_VIEW_PREFIX = "stats:user:view:daily:";
    private static final String USER_MONTHLY_VIEW_PREFIX = "stats:user:view:monthly:";
    private static final String ACTION_DAILY_COUNT_PREFIX = "stats:action:daily:";
    private static final String HOT_USERS_RANKING_KEY = "ranking:hot:users";
    
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");
    private static final DateTimeFormatter MONTH_FORMATTER = DateTimeFormatter.ofPattern("yyyyMM");

    /**
     * 记录用户被查看行为
     *
     * @param userId    被查看的用户ID
     * @param viewerId  查看者ID，可为null
     */
    public void recordUserView(Integer userId, Integer viewerId) {
        LocalDate today = LocalDate.now();
        String dateStr = today.format(DATE_FORMATTER);
        String monthStr = today.format(MONTH_FORMATTER);
        
        // 1. 记录每日用户被查看次数
        String dailyKey = USER_DAILY_VIEW_PREFIX + dateStr;
        redisUtil.incr(dailyKey + ":" + userId, 1);
        
        // 2. 记录每月用户被查看次数
        String monthlyKey = USER_MONTHLY_VIEW_PREFIX + monthStr;
        redisUtil.incr(monthlyKey + ":" + userId, 1);
        
        // 3. 更新用户热度排行榜
        rankingUtil.incrementScore(HOT_USERS_RANKING_KEY, userId, 1);
        
        // 4. 记录查看者的行为（如果有查看者ID）
        if (viewerId != null) {
            String actionKey = ACTION_DAILY_COUNT_PREFIX + dateStr + ":view";
            redisUtil.incr(actionKey, 1);
        }
    }
    
    /**
     * 获取用户今日热度
     *
     * @param userId 用户ID
     * @return 今日热度值
     */
    public long getUserDailyHeat(Integer userId) {
        String dateStr = LocalDate.now().format(DATE_FORMATTER);
        String key = USER_DAILY_VIEW_PREFIX + dateStr + ":" + userId;
        Object count = redisUtil.get(key);
        return count == null ? 0 : Long.parseLong(count.toString());
    }
    
    /**
     * 获取用户本月热度
     *
     * @param userId 用户ID
     * @return 本月热度值
     */
    public long getUserMonthlyHeat(Integer userId) {
        String monthStr = LocalDate.now().format(MONTH_FORMATTER);
        String key = USER_MONTHLY_VIEW_PREFIX + monthStr + ":" + userId;
        Object count = redisUtil.get(key);
        return count == null ? 0 : Long.parseLong(count.toString());
    }
    
    /**
     * 获取热门用户排行榜
     *
     * @param count 获取数量
     * @return 排行榜数据
     */
    public List<Map<String, Object>> getHotUsersRanking(int count) {
        return rankingUtil.getTopN(HOT_USERS_RANKING_KEY, count);
    }
    
    /**
     * 记录用户行为
     *
     * @param actionType 行为类型，如：view, like, comment, share
     * @param targetId   目标ID
     * @param userId     用户ID
     */
    public void recordUserAction(String actionType, Integer targetId, Integer userId) {
        LocalDate today = LocalDate.now();
        String dateStr = today.format(DATE_FORMATTER);
        
        // 1. 记录行为总数
        String actionCountKey = ACTION_DAILY_COUNT_PREFIX + dateStr + ":" + actionType;
        redisUtil.incr(actionCountKey, 1);
        
        // 2. 记录用户行为
        if (userId != null) {
            String userActionKey = "stats:user:" + userId + ":action:" + dateStr;
            redisUtil.incr(userActionKey + ":" + actionType, 1);
        }
        
        // 3. 记录目标被操作次数
        if (targetId != null) {
            String targetActionKey = "stats:target:" + targetId + ":" + actionType + ":" + dateStr;
            redisUtil.incr(targetActionKey, 1);
        }
    }
    
    /**
     * 获取今日行为统计
     *
     * @return 行为统计数据
     */
    public Map<String, Long> getDailyActionStats() {
        String dateStr = LocalDate.now().format(DATE_FORMATTER);
        String prefix = ACTION_DAILY_COUNT_PREFIX + dateStr + ":";
        
        Map<String, Long> stats = new HashMap<>();
        String[] actionTypes = {"view", "like", "comment", "share"};
        
        for (String actionType : actionTypes) {
            String key = prefix + actionType;
            Object count = redisUtil.get(key);
            stats.put(actionType, count == null ? 0 : Long.parseLong(count.toString()));
        }
        
        return stats;
    }
} 